package com.hnx.admin.intercept;

import com.hnx.admin.api.param.ParamValidator;
import com.hnx.admin.json.BaseForm;
import com.hnx.admin.utils.ServletUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.util.Objects;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/6/9   16:53:49 
描   述：
*/
@Component
@RequiredArgsConstructor
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class InsertParamInterceptor implements Interceptor {
    private final ParamValidator paramValidator;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        HttpServletRequest request = ServletUtil.getRequest();
        if(Objects.nonNull(request)) {
            MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
            SqlCommandType sqlCommandType = statement.getSqlCommandType();
            int ordinal = sqlCommandType.ordinal();
            Object arg = invocation.getArgs()[1];
            if (Objects.nonNull(arg)) {
                if (arg instanceof BaseForm) {
                    BaseForm entity = (BaseForm) arg;
                    if (ordinal == 1) {
                        paramValidator.setParam(entity);
                    }
                }
            }
        }
        return invocation.proceed();
    }
}
